package com.springsecurity.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import com.springsecurity.bean.Permission;
import com.springsecurity.dao.PermissionDao;

@Service
public class MyInvocationSecurityMetadataSourceService  implements
        FilterInvocationSecurityMetadataSource {

    @Autowired
    private PermissionDao permissionDao;

    private Set<String> perimssionUrls = new HashSet<>();

    /**
     * 加载权限表中所有权限
     */
    @PostConstruct
    public void loadResourceDefine(){
        List<Permission> Permissions = (List<Permission>) permissionDao.findAll();
        perimssionUrls = Permissions.stream().map(Permission::getUrl).collect(Collectors.toSet());
    }

    /**
     * 	此方法是为了判定用户请求的url 是否在权限表中，如果在权限表中，
     * 	则返回给 decide 方法，用来判定用户是否有此权限。如果不在权限表中则放行。
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
//        AntPathRequestMatcher matcher;
//        String resUrl;
        
        String uri = request.getRequestURI();
		
		AntPathMatcher antPathMatcher = new AntPathMatcher();
		List<ConfigAttribute> list = new ArrayList<ConfigAttribute>();
		for (String url : perimssionUrls) {
			if (StringUtils.isNotBlank(url) && antPathMatcher.match(url, uri)) {
				ConfigAttribute cfg = new SecurityConfig(url);
				list.add(cfg);
			}
		}
		return list;
		
//        for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
//            resUrl = iter.next();
//            matcher = new AntPathRequestMatcher(resUrl);
//            if(matcher.matches(request)) {
//                return map.get(resUrl);
//            }
//        }
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}